package cn.zf233.xcloud.exception;

import cn.zf233.xcloud.commom.Const;
import cn.zf233.xcloud.util.AspectLog;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpSession;

/**
 * Created by zf233 on 2020/11/4
 * 异常统一处理
 */
@ControllerAdvice
public class GlobalExceptionHandle {

    private final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandle.class);

    @ExceptionHandler(value = LoginException.class)
    public String doLoginException(Model model, Exception e) {
        logger.error(e.getMessage());
        e.printStackTrace();
        model.addAttribute(Const.SessionAttributeCode.ERROR_MSG, e.getMessage());
        model.addAttribute(Const.SessionAttributeCode.ERROR_BACK, "index");
        return "error";
    }

    @ExceptionHandler(value = UserDetailUpdateException.class)
    public String doUserDetailUpdateException(Model model, Exception e) {
        logger.error(e.getMessage());
        e.printStackTrace();
        model.addAttribute(Const.SessionAttributeCode.ERROR_MSG, e.getMessage());
        model.addAttribute(Const.SessionAttributeCode.ERROR_BACK, "home");
        return "error";
    }

    @ExceptionHandler(value = ShareException.class)
    public String doShareException(Model model, Exception e) {
        logger.error(e.getMessage());
        e.printStackTrace();
        model.addAttribute(Const.SessionAttributeCode.ERROR_MSG, e.getMessage());
        model.addAttribute(Const.SessionAttributeCode.ERROR_BACK, "index");
        return "error";
    }

    @ExceptionHandler(value = MaintainException.class)
    public String doShareException(HttpSession session, MaintainException e) {
        logger.error(e.getMessage());
        e.printStackTrace();
        session.setAttribute(Const.SessionAttributeCode.NOTICE_MSG, e.getMessage());
        session.setAttribute(Const.SessionAttributeCode.NOTICE_TITLE, "重试");
        session.setAttribute(Const.SessionAttributeCode.NOTICE_BACK, "/");
        return "notice";
    }

    @ExceptionHandler(value = Exception.class)
    public String doException(Model model, Exception e) {
        logger.error(e.getMessage());
        e.printStackTrace();
        model.addAttribute(Const.SessionAttributeCode.ERROR_MSG, e.getMessage());
        model.addAttribute(Const.SessionAttributeCode.ERROR_BACK, "index");
        model.addAttribute(Const.SessionAttributeCode.NOTICE_TITLE, "返回主页");
        return "error";
    }
}
